package com.ruoyi.doc.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.flowable.FlowableServiceUrl;
import com.ruoyi.common.kkfile.KkFileViewServiceUrl;
import com.ruoyi.common.ofbiz.OfbizBaseService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.doc.domain.Content;
import com.ruoyi.doc.service.IContentService;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.utils.OfbizContextUtil;
import org.apache.ofbiz.base.util.Base64;
import org.apache.ofbiz.base.util.UtilGenerics;
import org.apache.ofbiz.base.util.UtilMisc;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.service.GenericServiceException;
import org.apache.ofbiz.service.LocalDispatcher;
import org.apache.ofbiz.service.ServiceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 文档Service业务层处理
 *
 * @author yuanpingfang
 * @date 2021-03-31
 */
@Service
public class ContentServiceImpl extends OfbizBaseService implements IContentService {
    private static final Logger log = LoggerFactory.getLogger(ContentServiceImpl.class);

    @Autowired
    private FlowableServiceUrl flowableServiceUrl;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private KkFileViewServiceUrl kkFileViewServiceUrl;

    /**
     * 查询文档
     *
     * @param contentId 文档ID
     * @return 文档
     */
    @Override
    public Map<String, Object> selectContentById(String contentId) {
        LocalDispatcher dispatcher = getDispatcher();
        Map<String, Object> serverMap = null;
        try {
            serverMap = dispatcher.runSync("selectContentById", UtilMisc.toMap("contentId", contentId));
            if (!ServiceUtil.isSuccess(serverMap)) {
                return serverMap;
            }
            String serverUrl = serverConfig.getUrl();//因为端口是80，且前端没有配置上下文,所以拿到的就是不带端口的地址
            //String kkFileUrl = kkFileViewServiceUrl.getUrl();
            GenericValue contentGv = (GenericValue) serverMap.get("content");
            String objectInfo = contentGv.getString("objectInfo");
            //if(kkFileUrl.endsWith("/")){
            //    kkFileUrl = kkFileUrl.substring(0, kkFileUrl.length() - 1);
            //}
            // 目前都在一台机器,所以先以服务器的地址为准
            //判断服务器的地址是否带了端口号
            String[] serverUrlAry = serverUrl.split(":");
            if (serverUrlAry.length > 2) { // 代表带了端口
                serverUrl = serverUrl.substring(0, serverUrl.lastIndexOf(":"));
            }
            String kkFilePath = serverUrl + ":" + kkFileViewServiceUrl.getPort();
            String previewFileUrl = Base64.base64Encode(kkFilePath + objectInfo);
            serverMap.put("previewFileUrl", kkFilePath + "/onlinePreview?url=" + previewFileUrl);
        } catch (GenericServiceException e) {
            log.error("selectContentById Error", e);
            return ServiceUtil.returnError(e.getMessage());
        }
        return serverMap;
    }

    /**
     * 查询文档列表
     *
     * @param content 文档
     * @return 文档
     */
    @Override
    public Map<String, Object> selectContentList(Content content, Integer pageNum, Integer pageSize, String orderBy) {
        LocalDispatcher dispatcher = getDispatcher();
        Map<String, Object> context = new HashMap<>();
        context.put("content", content);
        context.put("pageNum", pageNum);
        context.put("pageSize", pageSize);
        context.put("orderBy", orderBy);
        try {
            return dispatcher.runSync("selectContentList", context);
        } catch (GenericServiceException e) {
            log.error("selectContentList Error", e);
            return ServiceUtil.returnError(e.getMessage());
        }
    }

    /**
     * 新增文档
     *
     * @param content 文档
     * @return 结果
     */
    @Override
    public Map<String, Object> insertContent(Content content) {
        LocalDispatcher dispatcher = getDispatcher();
        Map<String, Object> context = OfbizContextUtil.buildUserConext(UtilMisc.toMap("content", content));
        try {
            return dispatcher.runSync("createContentExt", context);
        } catch (GenericServiceException e) {
            log.error("createContentExt Error", e);
            return ServiceUtil.returnError(e.getMessage());
        }
    }

    /**
     * 修改文档
     *
     * @param content 文档
     * @return 结果
     */
    @Override
    public Map<String, Object> updateContent(Content content) {
        //content.setDescription(HtmlUtil.escape(content.getDescription()));//转移html特殊字符
        content.setCreatedStamp(null);
        content.setCreatedTxStamp(null);
        content.setLastUpdatedStamp(null);
        content.setLastUpdatedTxStamp(null);
        LocalDispatcher dispatcher = getDispatcher();
        try {
            Map<String, Object> context = OfbizContextUtil.buildUserConext(content);
            return dispatcher.runSync("updateContentExt", context);
        } catch (GenericServiceException e) {
            log.error("updateContentExt Error", e);
            return ServiceUtil.returnError(e.getMessage());
        }
    }

    /**
     * 批量删除文档
     *
     * @param contentIds 需要删除的文档ID
     * @return 结果
     */
    @Override
    public Map<String, Object> deleteContentByIds(String[] contentIds) {
        LocalDispatcher dispatcher = getDispatcher();
        try {
            return dispatcher.runSync("deleteContentByIds", UtilMisc.toMap("contentIds", contentIds));
        } catch (GenericServiceException e) {
            log.error("deleteContentByIds Error", e);
            return ServiceUtil.returnError(e.getMessage());
        }
    }

    /**
     * 删除文档信息
     *
     * @param contentId 文档ID
     * @return 结果
     */
    //@Override
    //public Map<String, Object> deleteContentById(String contentId)
    //{
    //    Map<String, Object> context = new HashMap<>();
    //    context.put("contentId", contentId);
    //    try {
    //        return dispatcher.runSync("removeContent", context);
    //    } catch (GenericServiceException e) {
    //        log.error("removeContent Error", e);
    //        return ServiceUtil.returnError(e.getMessage());
    //    }
    //}
    @Override
    public Map<String, Object> startWorkflowContentById(String contentId) {
        LocalDispatcher dispatcher = getDispatcher();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        Map<String, Object> context = new HashMap<>();
        context.put("processCode", "DocumentChangeProcess");
        context.put("auditType", "DocumentChange");
        context.put("businessKey", contentId);
        context.put("serviceName", "eoms-callback");//回调的方法类
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("applyUserId", user.getUserId().toString());
        userMap.put("applyUserName", user.getNickName());
        userMap.put("applyUserPost", "");
        context.put("userMap", userMap);
        Map<String, Object> returnMap = this.selectContentById(contentId);
        Object content = UtilGenerics.cast(returnMap.get("content"));
        context.put("businessMap", content);
        Map<String, Object> responseMap = flowableServiceUrl.doPost(flowableServiceUrl.getStartProcessInstanceByKey(), context);
        if (responseMap != null && Integer.parseInt(responseMap.get("code").toString()) == 200) {
            return ServiceUtil.returnSuccess();
        }
        return ServiceUtil.returnError("工作流启动失败！");
    }

    /**
     * @param contentIds
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @Title moveContent
     * @Description 移动文件或文件夹
     * @author yuanpingfang
     * @date 2021-4-20 22:33
     */
    @Override
    public Map<String, Object> moveContent(String targetContentId, String[] contentIds) {
        LocalDispatcher dispatcher = getDispatcher();
        try {
            Map<String, Object> context = OfbizContextUtil.buildUserConext(UtilMisc.toMap("targetContentId", targetContentId, "contentIds", contentIds));
            return dispatcher.runSync("moveContent", context);
        } catch (GenericServiceException e) {
            log.error("moveContent Error", e);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
}